﻿using System.Linq;

namespace Nxg.Blog.Core.Commands.Accounts {
    public class ChangePasswordCommand {
        public string AuthorId { get; set; }

        public string NewPassword { get; set; }

        public string NewPasswordConfirm { get; set; }

        public string OldPassword { get; set; }
    }

    public class ChangePasswordCommandInvoker : ICommandInvoker<ChangePasswordCommand, CommandResult> {
        private readonly DataContext _db;

        public ChangePasswordCommandInvoker (DataContext db) {
            _db = db;
        }

        public CommandResult Execute (ChangePasswordCommand command) {
            var author = _db.Author.FirstOrDefault (x => x.Id.ToString () == command.AuthorId);
            if (Hasher.GetMd5Hash (command.OldPassword) != author.HashedPassword) {
                return new CommandResult ("旧密码不正确!");
            }

            author.HashedPassword = Hasher.GetMd5Hash (command.NewPassword);
            _db.SaveChanges ();
            return CommandResult.SuccessResult;
        }
    }
}